const {
  queryFaultTypeOptions
} = require('../../api/faultType')
const {
  getAssetsByScanQrCodeId
} = require('../../api/assets')
const {
  queryAllAssetsType
} = require('../../api/assetsType')
const {
  uploadImg,
  addWorkOrder
} = require('../../api/workOrder')
const {
  WORK_ORDER_CREATE_MODE,
  WORDER_ORDER_CREATE_TYPE,
  USER_TYPE,
  SERVICE_MODE
} = require('../../constant/index')
const {
  getUserKind,
  getUserBaseInformation
} = require('../../utils/strorage')
const getSlot = require('../../utils/timeslotpicker')
const {
  clearEmptyKey
} = require('../../utils/clearEmptyKey')
const { FormatDate } = require('../../utils/FormDate')
const {
  to,
  getEventData,
  showToast,
  openLoading,
  closeLoading,
  routeWithToken
} = getApp()
Page({
  data: {
    fileList: [],
    qrCode: null,
    USER_TYPE,
    formData: {
      assetsTypeId: '',
      assetsTypeName: '',
      cuFaultTypeId: '',
      assetsId: '',
      faultImg: [],
      launchUserId: '',
      companyId: '',
      launchContent: '',
      appointmentTime: new FormatDate().format('yyyy-MM-dd') + ' ' + getSlot.getCurrentTimeSlot()
    },
    faultTypeOptions: [],
    assetsTypeOptions: [],
    userType: ''
  },

  onLoad() {
    const userType = getUserKind()
    this.setData({
      userType
    })

    if (userType === 'client' && !this.getQrCode()) {
      const userInfo = getUserBaseInformation();

      this.setData({
        ['formData.launchUserName']: userInfo.userName,
        ['formData.launchUserId']: userInfo.userId,
        ['formData.companyId']: userInfo.companyId,
        ['formData.companyName']: userInfo.companyName,
        ['formData.departmentId']: userInfo.departmentId,
        ['formData.departmentName']: userInfo.departmentName,
      })
    }

    this.getOptionsMap()
  },

  onCustomFormTypeChange(event) {
    const {
      type
    } = getEventData(event);
    this.setData({
      [`formData.${type}`]: event.detail
    })
    this.clearForm(type)
    if (type === 'assetsTypeId') {
      if (event.detail || event.detail === 0) {
        this.getFaultTypeOptions()
      }
    }
  },

  setUserData(data) {
    this.clearForm('launchUserName');
    this.setData(data)
  },

  clearForm(type) {
    let clearList = []
    let optionsList = []
    if (type === 'launchUserName') {
      clearList = ['companyName', 'companyId', 'departmentName', 'departmentId', 'assetsTypeId', 'assetsName', 'assetsId', 'cuFaultTypeId', 'launchUserId']
      optionsList = ['faultTypeOptions']
    }

    if (type === 'assetsTypeId') {
      clearList = ['assetsName', 'assetsId', 'cuFaultTypeId']
      optionsList = ['faultTypeOptions']
    }

    if (type === 'assetsName') {
      clearList = ['assetsName', 'assetsId']
    }

    for (const item of clearList) {
      this.setData({
        [`formData.${item}`]: ''
      })
    }

    for (const item of optionsList) {
      this.setData({
        [item]: ''
      })
    }
  },

  async getQueryAllAssetsType() {
    const [err, data] = await to(queryAllAssetsType({}))

    if (!err) {
      this.setData({
        assetsTypeOptions: data
      })
      return Promise.resolve()
    }
    return Promise.reject(err)
  },

  async getFaultTypeOptions() {
    const params = {
      assetsTypeId: this.data.formData.assetsTypeId,
      serviceMode: SERVICE_MODE.repair
    }
    openLoading()
    const [err, data] = await to(queryFaultTypeOptions(params))
    closeLoading()

    if (!err) {
      this.setData({
        faultTypeOptions: data
      })
      return Promise.resolve()
    }
    return Promise.reject(err)
  },

  onCustomLaunchUserNameClick() {
    routeWithToken(`/page-common/custom-user-page/index`)
  },

  onCustomAssetsNameClick() {
    routeWithToken(`/page-common/device-page/index?userId=${ this.data.formData.launchUserId }&assetsTypeId=${ this.data.formData.assetsTypeId }`)
  },

  setDeviceData(data) {
    this.setData(data);
  },

  getQrCode() {
    const qrCode = this.options.qrCode
    this.setData({
      qrCode
    })
    if (!qrCode) return null
    const list = qrCode.split('/')
    return list[list.length - 1]
  },

  async getDeviceInfo() {
    const qrCodeId = this.getQrCode()

    if (!qrCodeId) return Promise.resolve()
    const params = {
      qrCodeId
    }

    const [err, data] = await to(getAssetsByScanQrCodeId(params))

    if (!err) {
      this.setData({
        ['formData.companyId']: data.companyId,
        ['formData.companyName']: data.companyName,
        ['formData.departmentId']: data.departmentId,
        ['formData.departmentName']: data.departmentName,
        ['formData.assetsId']: data.assetsId,
        ['formData.assetsName']: data.assetsName,
        ['formData.launchUserId']: data.assetsUserId,
        ['formData.launchUserName']: data.userName,
        ['formData.assetsTypeId']: data.assetsTypeId,
        ['formData.assetsTypeName']: data.assetsTypeName,
      })
      this.getFaultTypeOptions()
      return Promise.resolve()
    } else {
      this.setData({
        qrCode: ''
      })
    }
    return Promise.reject(err)
  },

  async getOptionsMap() {
    openLoading()
    await to(Promise.all([this.getQueryAllAssetsType(), this.getDeviceInfo()]));
    closeLoading()
  },

  async uploadFile(file) {
    const [err, data] = await to(uploadImg({
      filePath: file
    }))
    if (!err) {
      return Promise.resolve(data)
    }
    return Promise.reject(err)
  },

  async handleSubmit() {
    const isCheck = this.checkValidate()
    if (!isCheck) return;
    const {
      fileList
    } = this.data;
    const [err, fileData] = await to(Promise.all(fileList.map(item => {
      const result = this.uploadFile(item);
      return result
    })))
    if (!err) {
      this.setData({
        ['formData.faultImg']: fileData
      }, () => {
        this.saveData()
      })
    }
  },

  checkValidate() {
    const rules = ['launchUserId', 'assetsTypeId', 'assetsId', 'cuFaultTypeId', 'launchUserId']
    const rulesLabel = ['请选择报修人员', '请选择资源类型', '请选择资源', '请选择故障事件'];
    for (const index in rules) {
      const arr = rules[index].split('.')
      const value = arr.reduce((result, key) => {
        return result[key]
      }, this.data.formData);

      if (!value && value !== 0) {
        showToast(rulesLabel[index]);
        return false
      }
    }
    if (this.data.userType === 'repair') {
      if (!this.data.formData.appointmentTime) {
        showToast('请选择预约上门时间');
        return false
      }
    }
    return true
  },

  async saveData() {
    const {
      formData,
      userType
    } = this.data
    let workOrderCreateUserType = WORK_ORDER_CREATE_MODE.CUSTOMER_CREATE
    if (userType === 'repair') {
      workOrderCreateUserType = WORK_ORDER_CREATE_MODE.MAINTAINER_CREATE
    }
    const time = getSlot(formData.appointmentTime);
    const params = {
      assetsTypeId: formData.assetsTypeId,
      cuFaultTypeId: formData.cuFaultTypeId,
      assetsId: formData.assetsId,
      faultImg: formData.faultImg,
      launchUserId: formData.launchUserId,
      companyId: [formData.companyId],
      launchContent: formData.launchContent,
      workOrderCreateMode: this.data.qrCode ? WORDER_ORDER_CREATE_TYPE.SCAN_MODE : WORDER_ORDER_CREATE_TYPE.NORMAL_MODE,
      appointmentTime: time.date,
      timeSlotCode: time.timeSlotCode,
      workOrderCreateUserType,
    }

    clearEmptyKey(params)
    openLoading()
    const [err] = await to(addWorkOrder(params))
    closeLoading()
    if (!err) {
      showToast({
        message: '保存成功',
        type: 'success',
        mask: true,
        onClose: () => {
          setTimeout(() => {
            wx.navigateBack({
              fail: () => {
                wx.reLaunch({
                  url: '/tabbar/index/index',
                })
              }
            })
          }, 1000)
        }
      })
    }
  },

  onFileChange(event) {
    this.setData({
      fileList: event.detail
    })
  }
})